<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 警告 -->
      <el-alert title="注意:只允许为第三级分类设置相关参数!" type="warning" show-icon />
      <div class="chios">
        选择商品分类:
        <el-cascader
          v-model="typeArr"
          :options="options"
          @change="chgCascader"
          :props="{ expandTrigger: 'hover', label: 'cat_name', value: 'cat_id' }"
        ></el-cascader>
      </div>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-change="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮  @click="dialogManyVisible = true"-->
          <el-button :disabled="typeArr.length !== 3" type="primary" size="small" @click="dialogManyVisible = true">
            添加参数
          </el-button>
          <!-- 表格 -->
          <el-table border style="width: 100%" :data="tableDataMany" row-key="attr-id">
            <el-table-column type="expand" width="80">
              <!-- 作用域插槽，获取一行的数据 -->
              <template v-slot="scope">
                <div>
                  <!-- close标签的关闭的是偶 -->
                  <el-tag
                    @close="handleTagClose(scope.row, i)"
                    v-for="(tag, i) in scope.row.attr_arr"
                    :key="i"
                    closable
                  >
                    {{ tag }}
                  </el-tag>
                  <!-- @keyup.enter.native="handleInputConfirm"    -->
                  <el-input
                    style="width: 50px"
                    class="input-new-tag"
                    v-model="inputValue"
                    v-if="scope.row.inputVisible"
                    size="small"
                    ref="saveTagInput"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                    + New Tag
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <!-- type="index" 使用序号 -->
            <el-table-column type="index" width="80"></el-table-column>
            <el-table-column prop="attr_name" label="参数名"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <div>
                  <!-- 修改 -->
                  <el-button type="primary" icon="EditPen" size="small"></el-button>
                  <!-- 删除 -->
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    @click="delCateAttrById(scope.row.cat_id, scope.row.attr_id)"
                  ></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态数据 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 表格 -->
          <el-table border style="width: 100%" :data="tableDataOnly" row-key="attr-id">
            <el-table-column type="expand" width="80">
              <!-- 作用域插槽，获取一行的数据 -->
              <template v-slot="scope">
                <div>
                  <!-- close标签的关闭的是偶 -->
                  <el-tag
                    @close="handleTagClose(scope.row, i)"
                    v-for="(tag, i) in scope.row.attr_arr"
                    :key="i"
                    closable
                  >
                    {{ tag }}
                  </el-tag>
                  <!-- @keyup.enter.native="handleInputConfirm"    -->
                  <el-input
                    style="width: 50px"
                    v-model="inputValue"
                    v-if="scope.row.inputVisible"
                    size="small"
                    ref="saveTagInput"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                    + New Tag
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <!-- type="index" 使用序号 -->
            <el-table-column type="index" width="80"></el-table-column>
            <el-table-column prop="attr_name" label="参数名"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <div>
                  <!-- 修改 -->
                  <el-button type="primary" icon="EditPen" size="small"></el-button>
                  <!-- 删除 -->
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    @click="delCateAttrById(scope.row.cat_id, scope.row.attr_id)"
                  ></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- dialogManyVisible true来控制dialog的显示 -->
    <el-dialog title="添加动态参数" v-model="dialogManyVisible" width="50%" @close="resetUser">
      <el-form ref="addManyForm2" :model="addManyForm" :rules="addManyRules" label-width="100px">
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="addManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogManyVisible = false">取 消</el-button>
      <el-button type="primary" @click="addCateAttr">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
// import type { TabsPaneContext } from 'element-plus'
import request from '@/util/request'
import { ElMessage, ElMessageBox } from 'element-plus'
const activeName = ref('many')

// 级联数据
const options = ref([])
// 分类参数id数组
const typeArr = ref([])
// 动态属性列表
const tableDataMany = ref([])
// 动态属性列表
const tableDataOnly = ref([])
// 控制添加动态对话框的显示
const dialogManyVisible = ref(false)
// 动态参数表单
const addManyForm = ref({
  attr_name: '',
  attr_sel: '',
})
const addManyForm1 = ref({
  attr_name: '',
  attr_sel: '',
})
const addManyForm2 = ref({})
const resetUser = () => {
  Object.assign(addManyForm.value, addManyForm1.value)
}
// 校验的数组
const addManyRules = {
  attr_name: [{ required: true, message: '请输入动态参数', trigger: 'blur' }],
}
// 接受的数组
const inputValue = ref('')
onMounted(() => {
  getCategoriesCascader()
})
// 获取级联数据,分类数据
const getCategoriesCascader = async () => {
  const { data, meta }: any = await request({
    url: 'categories',
    method: 'GET',
  })
  if (meta.status !== 200) {
    return ElMessage.error('获取参数错误')
  }
  options.value = data
  // console.log(data, meta);
}
const chgCascader = (val: string | any[]) => {
  if (val.length !== 3) {
    typeArr.value = []
    return
  }
  // 获取参数
  getCategoriesAttributes()
}

// 根据id获取动态|静态的列表
const getCategoriesAttributes = async () => {
  const { data, meta }: any = await request({
    url: `categories/${typeArr.value[2]}/attributes`,
    params: { sel: activeName.value },
    method: 'get',
  })
  if (meta.status !== 200) {
    return ElMessage.error('获取分类参数失败')
  }
  if (activeName.value === 'many') {
    // data[0].attr_vals       // 在赋值之前,需要转化数据
    data.forEach((obj: any) => {
      // 控制输入框是否显示的
      obj.inputVisible = false
      // 转化好的数据重复绑定到 属性
      if (obj.attr_vals.trim() === '') {
        // 重新添加的数据
        obj.attr_arr = []
      } else {
        obj.attr_arr = obj.attr_vals.split(' ')
      }
    })
    tableDataMany.value = data
  } else {
    data.forEach((obj: any) => {
      // 控制输入框是否显示的
      obj.inputVisible = false
    })
    tableDataOnly.value = data
  }
}
// 标签页点击切换了
const tabClick = () => {
  // console.log("切换了", this.activeName);
  // 重新获取参数的列表数据| 动态|静态
  getCategoriesAttributes()
}
// 根据参数id和属性id来删除参数的属性
const delCateAttrById = async (cate_id: any, attr_id: any) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      // 确定的按钮的时候删除数据
      const { meta }: any = await request({
        url: `categories/${cate_id}/attributes/${attr_id}`,
        method: 'delete',
      })
      if (meta.status !== 200) {
        return ElMessage.error('删除失败')
      }
      // 提示成功
      ElMessage.success('删除成功')
      // 刷新页面
      getCategoriesAttributes()
    })
  } catch (error) {
    return ElMessage.info('取消删除')
  }
}
// 添加动态参数
const addCateAttr = async () => {
  // console.log(this.$refs);
  // 调用校验方法
  addManyForm2.value.validate(async (valid: any) => {
    // valid==true 通过校验,
    if (!valid) {
      return ElMessage.error('请填写正确数据')
    }
    addManyForm.value.attr_sel = activeName.value
    const { meta }: any = await request({
      url: `categories/${typeArr.value[2]}/attributes`,
      method: 'POST',
      data: addManyForm.value,
    })
    if (meta.status !== 201) {
      return ElMessage.error('添加失败')
    }
    ElMessage.success('添加成功')
    // 关闭对话框
    dialogManyVisible.value = false
    // 刷新页面
    getCategoriesAttributes()
  })
}
// 当点击的时候显示input 输入框
const saveTagInput = ref('')
const showInput = (obj: any) => {
  // 变成输入框
  obj.inputVisible = true
  // 让输入框获取光标,页面的数据,dom重新渲染,才会执行
  nextTick(() => {
    saveTagInput.value.focus()
  })
  // setTimeout(() => {
  //   this.$refs.saveTagInput.focus();
  // }, 1000);
}
// 失去焦点的时候,重新变成按钮
const handleInputConfirm = async (obj: any) => {
  // 将input去掉
  obj.inputVisible = false
  // 如果是空的 立即结束
  if (!inputValue.value) {
    return
  }
  obj.attr_arr.push(inputValue.value)
  inputValue.value = ''
  obj.attr_vals = obj.attr_arr.join(' ')
  const { meta }: any = await request({
    url: `categories/${obj.cat_id}/attributes/${obj.attr_id}`,
    // 修改的方法是put  查询|获取get  添加post  删除delete
    method: 'PUT',
    data: obj,
  })
  if (meta.status !== 200) {
    return ElMessage.error('更新属性失败')
  }
  return ElMessage.success('更新成功')
}
const handleTagClose = (obj: { attr_arr: any[] }, i: any) => {
  // 根据i删除数组的数据
  obj.attr_arr.splice(i, 1)
  // 更新参数的属性
  updateCateAttr(obj)
}
// 更新参数的属性
const updateCateAttr = async (obj: any) => {
  obj.attr_vals = obj.attr_arr.join(' ')
  const { meta }: any = await request({
    url: `categories/${obj.cat_id}/attributes/${obj.attr_id}`,
    // 修改的方法是put  查询|获取get  添加post  删除delete
    method: 'PUT',
    data: obj,
  })
  if (meta.status !== 200) {
    return ElMessage.error('更新属性失败')
  }
  return ElMessage.success('更新成功')
}
</script>

<style scoped lang="scss">
.box-card {
  margin-top: 20px;

  .chios {
    font-family: '宋体';
    font-style: oblique;
    margin-top: 10px;
    font-size: 20px;
  }

  .el-tabs {
    .el-tag {
      margin-right: 10px;
    }
  }
}
</style>
